import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
import { useLoading } from '@sa/hooks';
import { fetchGetUserInfo, fetchLogin } from '@/service/api';
import { useRouterPush } from '@/hooks/common/router';
import { localStg } from '@/utils/storage';
import { SetupStoreId } from '@/enum';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken } from './shared';

export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
  const route = useRoute();
  const authStore = useAuthStore();
  const routeStore = useRouteStore();
  const tabStore = useTabStore();
  const { toLogin, redirectFromLogin } = useRouterPush(false);
  const { loading: loginLoading, startLoading, endLoading } = useLoading();

  const token = ref(getToken());

  const userInfo: Api.Auth.UserInfo = reactive({
    userId: '',
    userName: '',
    roles: [],
    buttons: []
  });

  // 库存助手特有数据
  const inventoryUserRights = ref<Api.Auth.InventoryUserRights | null>(null);
  const inventorySystemSetting = ref<Api.Auth.InventorySystemSetting | null>(null);

  /** is super role in static route */
  const isStaticSuper = computed(() => {
    const { VITE_AUTH_ROUTE_MODE, VITE_STATIC_SUPER_ROLE } = import.meta.env;

    return VITE_AUTH_ROUTE_MODE === 'static' && userInfo.roles.includes(VITE_STATIC_SUPER_ROLE);
  });

  /** Is login */
  const isLogin = computed(() => Boolean(token.value));

  /** Reset auth store */
  async function resetStore() {
    recordUserId();

    clearAuthStorage();

    authStore.$reset();

    if (!route.meta.constant) {
      await toLogin();
    }

    tabStore.cacheTabs();
    routeStore.resetStore();
  }

  /** Record the user ID of the previous login session Used to compare with the current user ID on next login */
  function recordUserId() {
    if (!userInfo.userId) {
      return;
    }

    // Store current user ID locally for next login comparison
    localStg.set('lastLoginUserId', userInfo.userId);
  }

  /**
   * Check if current login user is different from previous login user If different, clear all tabs
   *
   * @returns {boolean} Whether to clear all tabs
   */
  function checkTabClear(): boolean {
    if (!userInfo.userId) {
      return false;
    }

    const lastLoginUserId = localStg.get('lastLoginUserId');

    // Clear all tabs if current user is different from previous user
    if (!lastLoginUserId || lastLoginUserId !== userInfo.userId) {
      localStg.remove('globalTabs');
      tabStore.clearTabs();

      localStg.remove('lastLoginUserId');
      return true;
    }

    localStg.remove('lastLoginUserId');
    return false;
  }

  /**
   * Login
   *
   * @param userName User name
   * @param password Password
   * @param [redirect=true] Whether to redirect after login. Default is `true`
   */
  async function login(userName: string, password: string, redirect = true) {
    startLoading();

    const { data: loginToken, error } = await fetchLogin(userName, password);

    if (!error) {
      const pass = await loginByToken(loginToken);

      if (pass) {
        // Check if the tab needs to be cleared
        const isClear = checkTabClear();
        let needRedirect = redirect;

        if (isClear) {
          // If the tab needs to be cleared,it means we don't need to redirect.
          needRedirect = false;
        }
        await redirectFromLogin(needRedirect);

        window.$notification?.success({
          title: $t('page.login.common.loginSuccess'),
          content: $t('page.login.common.welcomeBack', { userName: userInfo.userName }),
          duration: 4500
        });
      }
    } else {
      resetStore();
    }

    endLoading();
  }

  async function loginByToken(loginToken: Api.Auth.LoginToken) {
    // 1. stored in the localStorage, the later requests need it in headers
    localStg.set('token', loginToken.token);
    localStg.set('refreshToken', loginToken.refreshToken);

    // 2. get user info
    const pass = await getUserInfo();

    if (pass) {
      token.value = loginToken.token;

      return true;
    }

    return false;
  }

  async function getUserInfo() {
    const { data: info, error } = await fetchGetUserInfo();

    if (!error) {
      // update store
      Object.assign(userInfo, info);

      return true;
    }

    return false;
  }

  async function initUserInfo() {
    const hasToken = getToken();

    if (hasToken) {
      // 检查是否是库存助手系统
      const storedRights = localStg.get('inventoryRights');

      if (storedRights) {
        // 库存助手系统，从 localStorage 恢复数据

        // 恢复库存数据
        inventoryUserRights.value = storedRights;
        inventorySystemSetting.value = localStg.get('inventorySetting');

        // 恢复用户信息（如果有）
        const storedUserInfo = localStg.get('userInfo');
        if (storedUserInfo) {
          Object.assign(userInfo, storedUserInfo);
        } else {
          // 如果没有用户信息，使用默认的库存助手角色
          Object.assign(userInfo, {
            userId: 'inventory-user',
            userName: '库存助手用户',
            roles: ['inventory-user'],
            buttons: []
          });
        }

        token.value = hasToken;
      } else {
        // 普通系统，使用原有逻辑
        const pass = await getUserInfo();

        if (!pass) {
          resetStore();
        }
      }
    }
  }

  // 库存助手专用登录方法
  async function loginByInventoryToken(loginResult: any) {
    try {
      // 1. 验证必要的登录数据
      if (!loginResult.token) {
        return false;
      }

      if (!loginResult.data || !loginResult.data.userName) {
        return false;
      }

      // 2. 存储token
      localStg.set('token', loginResult.token);
      localStg.set('refreshToken', loginResult.token); // 库存助手没有refresh token，用token代替

      // 3. 适配用户信息结构，确保包含系统需要的字段
      const adaptedUserInfo = {
        // 保留原有的库存助手特有字段
        ...loginResult.data,
        // 覆盖系统需要的标准字段
        userId: loginResult.data.userId || loginResult.data.userName,
        userName: loginResult.data.userName,
        roles: ['inventory-user'], // 给库存助手用户分配默认角色
        buttons: loginResult.data.authBtnList || [], // 使用库存助手的按钮权限
        // 确保包含权限相关字段  
        identity: loginResult.data.identity || 0,
        rights: loginResult.data.rights || [],
        // 其他库存助手特有字段
        avatarUrl: loginResult.data.avatarUrl,
        mobilePhoneNumber: loginResult.data.mobilePhoneNumber,
        nickName: loginResult.data.nickName,
        objectId: loginResult.data.objectId,
        sex: loginResult.data.sex,
        version: loginResult.data.version,
        vipTime: loginResult.data.vipTime,
        disabled: loginResult.data.disabled,
        selectStocks: loginResult.data.selectStocks,
        selectCustoms: loginResult.data.selectCustoms,
        masterId: loginResult.data.masterId,
        master: loginResult.data.master,
        staffRole: loginResult.data.staffRole,
        staffRoleId: loginResult.data.staffRoleId,
        isMockVip: loginResult.data.isMockVip,
        uid: loginResult.data.uid
      };

      Object.assign(userInfo, adaptedUserInfo);

      // 4. 存储库存助手特有数据
      inventoryUserRights.value = loginResult.rights || {};
      inventorySystemSetting.value = loginResult.setting || {};

      // 5. 存储到localStorage (保持兼容性)
      localStg.set('inventoryRights', loginResult.rights || {});
      localStg.set('inventorySetting', loginResult.setting || {});
      localStg.set('userInfo', adaptedUserInfo); // 保存用户信息供刷新时恢复

      token.value = loginResult.token;

      // 6. 初始化路由系统 (库存助手使用静态路由模式)
      try {
        await routeStore.initConstantRoute();

        if (import.meta.env.VITE_AUTH_ROUTE_MODE === 'static') {
          // 静态路由模式，直接初始化权限路由
          await routeStore.initAuthRoute();
        }
      } catch (error) {
        // 即使路由初始化失败也不阻止登录，让用户先进入系统
      }

      return true;
    } catch (error) {
      return false;
    }
  }

  // 获取库存助手权限
  function getInventoryRights() {
    if (!inventoryUserRights.value) {
      const stored = localStg.get('inventoryRights');
      if (stored) {
        inventoryUserRights.value = stored;
      }
    }
    return inventoryUserRights.value;
  }

  // 检查是否可以查看成本价
  const canSeeCostPrice = computed(() => {
    const rights = getInventoryRights();
    return rights?.good?.canSeeCostprice || false;
  });

  // 检查是否只能看到自己的订单
  const seeMyOrderOnly = computed(() => {
    const rights = getInventoryRights();
    return rights?.order?.seeMyOrder || false;
  });

  return {
    token,
    userInfo,
    inventoryUserRights,
    inventorySystemSetting,
    isStaticSuper,
    isLogin,
    loginLoading,
    canSeeCostPrice,
    seeMyOrderOnly,
    resetStore,
    login,
    loginByInventoryToken,
    getInventoryRights,
    initUserInfo
  };
});
